package demo.springcloud.webflux.rest.filter;

import demo.springcloud.webflux.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
public class MyWebFilters implements WebFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        String token;
        HttpHeaders headers = serverWebExchange.getRequest().getHeaders();
        if (headers.containsKey("Authorization") && headers.get("Authorization").get(0).contains("Bearer")) {
            token = headers.get("Authorization").get(0).substring(7, headers.get("Authorization").get(0).length());
            System.out.println("token: " + token);
            Claims claims = jwtUtil.parseJWT(token);
            if(claims!=null){
                String userId = claims.getId();
                serverWebExchange.getAttributes().put("userId", userId);
            }
        }
        return webFilterChain.filter(serverWebExchange);
    }
}
